package com.wl.lib.mvi

import androidx.lifecycle.LifecycleCoroutineScope
import kotlinx.coroutines.flow.MutableSharedFlow
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.SharedFlow
import kotlinx.coroutines.flow.asStateFlow


// Created by wangliang on 2024/4/28.

/**
 * ViewModel 中 更新状态数据
 */
fun <T> MutableStateFlow<T>.setState(reducer: T.() -> T) {
    this.value = this.value.reducer()
}

fun <T> MutableStateFlow<T>.observeState(
    lifecycleScope: LifecycleCoroutineScope,
    action: (T) -> Unit
) {

    // 这里虽然被废弃，官方说了会有浪费，但是目前我们的需求是当 onStarted 时候执行，否则就挂起，当 onStart 后继续执行
    // 当 onDestroy 取消
    // TODO 这里目前无法达到 launchWhenStarted 效果，会产生粘性，每次 onStart 都会触发重绘
    //        lifecycleScope.launch {
    //            var isHandleCompleted = false
    //            lifecycle.repeatOnLifecycle(Lifecycle.State.STARTED) {
    //                Log.d("WLTest", "handle block $isHandleCompleted")
    //                if (isHandleCompleted)
    //                    return@repeatOnLifecycle
    //                block()
    //                isHandleCompleted = true
    //            }
    //        }
    lifecycleScope.launchWhenStarted {
        asStateFlow().collect {
            action.invoke(it)
        }
    }
}

suspend fun <T> MutableSharedFlow<T>.postEvent(event: T) {
    this.emit(event)
}

fun <T> SharedFlow<T>.observeEvent(lifecycleScope: LifecycleCoroutineScope, action: (T) -> Unit) {
    lifecycleScope.launchWhenStarted {
        this@observeEvent.collect {
            action.invoke(it)
        }
    }
}
